<?php
include('class/class_connect.php');
include('class/class_page.php');
include('class/city_rus.php');
include('class/class_form.php');
include('class/class_checkGetData.php');
include('includes/rubriks.php');
foreach($_GET as $key=>$val)
{
	$_GET[$key]=checkGetData::safetyCheck($val);
}
$aCheckData=new checkGetData('main');
$aCheckData->checkTableId('nets', $_GET['id']);
session_start();
if(!$_SESSION['login'])
{
	header('location: registr.php?city='.$_GET['city']);
	exit;
}
$aConnect=new connect('main');
$row=mysql_fetch_array($aConnect->select_all('nets', "WHERE id='".$_GET['id']."'"));
if(strtolower($row['user'])!=strtolower($_SESSION['login']))
{
	echo ('
	<center>
		<h1>У Вас нет доступа к запрашиваемой странице!</h1>
		<a href="index.php">На главную</a>
		</center>
	');
}
$aForm=new form();
$warning=false;
if($_POST['undoFirms'])unset($_POST);
if($_POST['editFirms'])
{	if(!$_POST['cityId'])
		$warning='Вы не выбрали ни один город для изменения!';
	if($_POST['division'] || $_POST['subdiv'])
	{
		if(!$warning)
		{
			$checkDiv=false;
			$checkSubdiv=false;
			foreach($divises as $division=>$divSubs)
			{
				if($division==$_POST['division'])$checkDiv=true;
				for($i=0; $i<count($divSubs); $i++)
					if($divSubs[$i]==$_POST['subdiv'])$checkSubdiv=true;
			}
		}
		if(!$warning)
			if(!$checkDiv)$warning='Недопустимая рубрика!';
		if(!$warning)
			if(!$checkSubdiv)$warning='Недопустимый раздел рубрики!';
	}
	if(!$warning && isset($_POST['name']))
		$warning=$aForm->checkInput($_POST['name'], 'название', 'name', $row['name'], 80, 1, "", "\" ` ^ ~ < > \r\n", 'o (Только русские и английские буквы и цифры и -!@#*?&$()\'.,)');
	if(!$warning && isset($_POST['short']))
		$warning=$aForm->checkInput($_POST['short'], 'краткое описание', 'short', $row['short'], 80, 2, "", "\" ` ^ ~ < > \r\n", 'o (Только русские и английские буквы и цифры и -@#&()\'.,)');
	if($_POST['link'])
	{
		$_POST['link']=str_replace('http://', '', $_POST['link']);
		$_POST['link']=str_replace('https://', '', $_POST['link']);
		$_POST['link']=str_replace('www.', '', $_POST['link']);
	}
	if(!$warning && isset($_POST['link']) && $_POST['link']!='')
		$warning=$aForm->checkInput($_POST['link'], 'веб-сайт', 'link', $row['link'], 60, 5, "", ", \" ` ^ ~ < > \r\n ! № % : ?   =  $ &  [ ] / + \\ { } [ ] ;  \'", ' (Только буквы,цифры и -_.)');
	if(!$warning && isset($_POST['address']))
		$warning=$aForm->checkInput($_POST['address'], 'адрес', 'address', $row['address'], 100, 1, "", "\" ` ^ ~", 'o');
	if(!$warning && isset($_POST['phone']))
		$warning=$aForm->checkInput($_POST['phone'], 'телефон', 'phone', $row['phone'], 60, 1, "", "\" ` ^ ~", 'o');
	if(!$warning && $_POST['textTitle']!='')
		$warning=$aForm->checkInput($_POST['textTitle'], 'заголовок текста', 'textTitle', '', 80, 0, "", " \" \r\n ` ^ ~", ' (все символы кроме "`^~)');
	if(!$warning && $_POST['stext']!='')
		$warning=$aForm->checkInput($_POST['stext'], 'текст', 'stext', '', 6000, 0, "", " \" ` ^ ~", ' (все символы кроме "`^~)');

	if(!$warning)//все поля заполнены правильно
	{
		if($_POST['subdiv'] && $_POST['division'])
		{
			$data['division']=$_POST['division'];
			$data['subdiv']=$_POST['subdiv'];
		}
		if($_POST['name'])$data['name']=$_POST['name'];
		if($_POST['short'])$data['short']=$_POST['short'];
		if($_POST['link'])$data['link']=$_POST['link'];
		if($_POST['text_title'])$data['text_title']=$_POST['text_title'];
		if($_POST['stext'])$data['stext']=$_POST['stext'];
		if($data)//сделаны изменения
		{
			if($data)
			{
				foreach($data as $r=>$v)
				{
					$dataTo[]=$r."='".$v."'";
				}
				if($dataTo)$dataToUpdate=implode(', ', $dataTo);
			}
			if($dataToUpdate)
			{				foreach($_POST['cityId'] as $key=>$cityId)
				{					$cityIdEls=explode('^', $cityId);
					$city=$cityIdEls[0];
					$id=$cityIdEls[1];
					$aConnect=new connect('f');
					$row=mysql_fetch_array($aConnect->select_all($city, "WHERE id='$id'"));
					$aConnect->update_data($city, $dataToUpdate, "WHERE id='".$id."'"); //обновляем данные фирмы
					if($_POST['name'] && $_POST['name']!=$row['name'])//если изменено имя фирмы, меняем имя фирмы в данных пользователя
					{						$aConnect=new connect('main');
						$aRow=mysql_fetch_array($aConnect->select_all('users', "WHERE login='".$_SESSION['login']."'"));
						if($aRow['firms'])
						{
							$mallsArray=explode(',', $aRow['firms']);
							for($i=0; $i<count($mallsArray); $i++)
							{
								$mallsInfoArray=explode('^', $mallsArray[$i]);
								if($mallsInfoArray[1]==$row['id'])$mallsInfoArray[2]=$_POST['name'];
								$mallsArray[$i]=implode('^', $mallsInfoArray);
							}
							$newMalls=implode(',', $mallsArray);
						}
						$aConnect->update_data('users', "firms='".$newMalls."'", "WHERE login='".$_SESSION['login']."'");
					}

				    ($_POST['name'])?$name=$_POST['name']:$name=$row['name'];
				    ($_POST['subdiv'])?$subdiv=$_POST['subdiv']:$subdiv=$row['subdiv'];
					$aConnect=new connect('m');

					if($_POST['subdiv'] || $_POST['name'])//если меняем имя или рубрику, меняем их в данных торговых центров, если есть привязки
					{
						if($row['malls'])
						{
							$mall=explode(',', $row['malls']);
							for($i=0; $i<count($mall); $i++)
							{
								$mrow=mysql_fetch_array($aConnect->select_all($city, "WHERE id='".$mall[$i]."'"));
								if($mrow['firms'])
								{
									$firms=explode('|', $mrow['firms']);
									for($j=0; $j<count($firms); $j++)
									{
										$firmsEls=explode('^', $firms[$j]);
										if($firmsEls[0]==$row['id'])
										{
											if($_POST['name'])$firmsEls[1]=$_POST['name'];
											if($_POST['subdiv'])$firmsEls[2]=$_POST['subdiv'];
										}
										$firms[$j]=implode('^', $firmsEls);
									}
									$mrow['firms']=implode('|', $firms);
								}
								$aConnect->update_data($city, "firms='".$mrow['firms']."'", "WHERE id='".$mall[$i]."'");
							}
						}
					}
					if($_POST['imgName'])
					{
						if(file_exists($_POST['imgName'].'.jpg'))
						{
							copy($_POST['imgName'].'.jpg', 'pictures/firmspics/'.$city.'/'.$row['id'].'.jpg');
						}
						if(file_exists($_POST['imgName']))
						{
							copy($_POST['imgName'], 'pictures/firmspics/'.$city.'/'.$row['id'].'.jpg');
						}
					}
				}
			}
		}
		$data=array();
		if($_POST['name'])$data['name']=$_POST['name'];
		if($_POST['short'])$data['short']=$_POST['short'];
		if($_POST['link'])$data['link']=$_POST['link'];
		if($_POST['address'])$data['address']=$_POST['address'];
		if($_POST['phone'])$data['phone']=$_POST['phone'];
		if($_POST['text_title'])$data['text_title']=$_POST['text_title'];
		if($_POST['stext'])$data['stext']=$_POST['stext'];
		$aConnect=new connect('main');
		$row=mysql_fetch_array($aConnect->select_all('nets', "WHERE id='".$_GET['id']."'"));
		if($_POST['name'])
		{			$cities=explode('|', $row['cities']);
			foreach($cities as $key=>$cityIdName)
			{				$cityIdNameEl=explode('^', $cityIdName);
				if(in_array($cityIdNameEl[0].'^'.$cityIdNameEl[1], $_POST['cityId']))
					$newCityIdName[]=$cityIdNameEl[0].'^'.$cityIdNameEl[1].'^'.$_POST['name'];
				else $newCityIdName[]=$cityIdName;			}
			$cities=implode('|', $newCityIdName);
			$data['cities']=$cities;		}

		if($data)
		{
			foreach($data as $r=>$v)
			{
				$dataTo[]=$r."='".$v."'";
			}
			if($dataTo)$dataToUpdate=implode(', ', $dataTo);
		}
		if($dataToUpdate)
		{
			$aConnect->update_data('nets', $dataToUpdate, "WHERE id='".$_GET['id']."'");		}
		if($_POST['imgName'])
		{
			if(file_exists($_POST['imgName']))
			{
				rename($_POST['imgName'], 'pictures/netspics/'.$row['id'].'.jpg');
			}
			if(file_exists($_POST['imgName'].'.jpg'))
			{
				rename($_POST['imgName'].'.jpg', 'pictures/netspics/'.$row['id'].'.jpg');
			}
		}
		header('location: netscabinet.php?city='.$_GET['city'].'&id='.$row['id']);
	}
}
$aConnect=new connect('main');
$row=mysql_fetch_array($aConnect->select_all('nets', "WHERE id='".$_GET['id']."'"));
$aForm=new  form();
class aFirmPage extends page
{
	var $warning;
	var $row=array();
	function __construct($warning, $row=array())
	{
		$this->warning=$warning;
		$this->row=$row;
		parent::__construct();
	}
	function title()
	{
		echo 'Редактировать сеть '.$this->row['name'];
	}
	function maincontent()
	{
		$aForm=new  form();
		$aForm->includeStyle();
		//$aForm->includeScript();
		$cityRus=new city_rus_class();
		$imgName='temp'.rand();
		//if(!$_POST['imgName'])$_POST['imgName']='pictures/nologo.jpg';
		if(file_exists('pictures/netspics/'.$this->row['id'].'.jpg') && !$_POST['imgName'])
			 $_POST['imgName']='pictures/netspics/'.$this->row['id'].'.jpg';
		echo ('
		<script type="text/javascript" src="scripts/editNets.js">
		</script>
		<script type="text/javascript" src="jquery/ajaxUpload.js">
  		</script>
  		<script type="text/javascript" src="scripts/chooseSubdivForm.js">
		</script>
		<link rel="stylesheet" type="text/css" href="style/editFirms.css" />
		<div class="route">
			<div class="routeEl">
				<a href="pcabinet.php?city='.$_GET['city'].'">Личный кабинет</a>
			</div>
			<div class="routeEl">
				<a href="my_nets.php?city='.$_GET['city'].'">Мои сети</a>
			</div>
			<div class="routeEl">
				<a href="netscabinet.php?city='.$_GET['city'].'&id='.$_GET['id'].'">'.$this->row['name'].'</a>
			</div>
			<div class="routeEl">
				Редактировать
			</div>
		</div>
		  <div class="form" align="center">
		  <h3>Редактировать '.$this->row['short'].' '.$this->row['name'].'</h3>
		   <form method="post" id="editFirms" name="editFirms" action="" autocomplete="off">
		   		<input name="city" type="hidden" value="'.$_GET['city'].'" id="city">
		   		<center id="warning">&nbsp;'.$this->warning.'</center>
		   		<div class="myform">
			   		<div class="signature">
			   	 		Логотип:
			   	 	</div>
			   		<div id="avatar">
				     	<div id="upload">
				 			<span id="span" class="loadButton" imgName="'.$imgName.'">Изменить</span>
				 		</div>
				 		<div id="preview">
		   	 				<img src="'.$_POST['imgName'].'" />
		   	 				<input type="hidden" name="imgName" value="'.$_POST['imgName'].'" />
		   	 				<span id="status"></span>
				    	</div>
			   	 	</div>
		   	 	</div>
		   	 	<div class="myform">
			 	<div class="signature">
					Рубрика:
				</div>
				<br />
				');
                @include('includes/rubriks.php');
				$subdiv=$this->row['subdiv'];
					foreach($divises as $divKey=>$divSubdives)
					{
						if(in_array($subdiv, $divSubdives))
						{
							$division=$divKey;
							break;
						}
					}
					echo ('
					<div class="chooseSubdiv">
						<div class="division" id="division"><div class="curDivision">'.$division.'</div><input name="division" id="divisionInput" type="hidden" value="'.$this->row['division'].'"></div>
						<div class="subdiv" id="firstsubdiv"><div class="curSubdiv">'.$subdiv.'</div><input name="subdiv" id="subdiv" type="hidden" value="'.$this->row['subdiv'].'"></div>
					</div>
			 </div>
		   	 	<div class="myform">
			   	 	<div class="signature">
			   	 		Название:
			   	 	</div>
			   		<div id="name" class="edit" value="'.$this->row['name'].'">
			   			'.$this->row['name'].'<br /><but class="but">изменить</but>
			   		</div>
				</div>
		   	 	<div class="myform">
			   		<div class="signature">
			   	 		Краткое описание:
			   	 	</div>
			   		<div id="short" class="edit" value="'.$this->row['short'].'">
			   			'.$this->row['short'].'<br /><but class="but">изменить</but>
			   		</div>
				</div>
				<div class="myform">
			   		<div class="signature">
			   	 		Веб-сайт:
			   	 	</div>
			   		<div id="link" class="edit" value="'.$this->row['link'].'">
			   			'.$this->row['link'].'<br /><but class="but">изменить</but>
			   		</div>
				</div>
		   	 	<div class="myform">
			   		<div class="signature">
			   	 		Адрес центрального офиса:
			   	 	</div>
			   	 	<div id="address" class="edit" value="'.$this->row['address'].'">
			   			'.$this->row['address'].'<br /><but class="but">изменить</but>
			   		</div>
					<br />
			   		<div class="signature">
			   	 		Телефон:
			   	 	</div>
			   	 	<div id="phone" class="edit" value="'.$this->row['phone'].'">
			   			'.$this->row['phone'].'<br /><but class="but">изменить</but>
			   		</div>
				</div>
		   	 	<div class="myform">
			   		<div class="signature">
			   	 		Заголовок текста:
			   	 	</div>
			   		<div id="text_title" class="edit" value="'.$this->row['text_title'].'">
			   			'.$this->row['text_title'].'<br /><but class="but">изменить</but>
			   		</div>
			   		<br /><br />
			   		<div class="signature">
			   	 		Текст:
			   	 	</div>
			   		<div id="text" class="edit" value="'.$this->row['stext'].'">
			   			'.$this->row['stext'].'<br /><but class="but">изменить</but>
			   		</div>

				</div>
				<div class="myform">
			   		<div class="signature">
			   	 		Отметьте города, в которых будут сделаны изменения:
			   	 	</div>
			   	 	<div class="cityCheck">
			   	 		<div id="allCities">
			   	 			Все города сети<input name="allCities" class="allCities" type="checkbox" value="1" checked="checked">
			   	 		</div>
			   	 		<div id="showCities">
			   	 			Выбрать города
			   	 		</div>
			   	 		<div id="cities">
			   	 			<table>
			   	 	');
					   	 	$cities=explode('|', $this->row['cities']);
					   	 	foreach($cities as $key=>$city)
					   	 	{					   	 		$cityEls=explode('^', $city);
					   	 		$c=$cityEls[0];
					   	 		$id=$cityEls[1];
					   	 		$name=$cityEls[2];
					   	 		echo ('
					   	 		<tr>
					   	 			<td width="170">
					   	 			'.$cityRus->city_rus_im($c).'
					   	 			</td>
					   	 			<td width="50">
					   	 				<input name="cityId[]" class="cityCheckBox" type="checkbox" value="'.$c.'^'.$id.'" checked="checked">
									</td>
								</tr>
					   	 		');							}
							echo ('
							</table>
			   	 		</div>
			   	 	</div>
				</div>
                <input type="submit" value="Сохранить" class="button button-blue" name="editFirms">
                <a href="netscabinet.php?city='.$_GET['city'].'&id='.$_GET['id'].'" class="button button-blue">Отменить</a>
		   </form>

		  </div>
		');
	}
}

$aPage=new aFirmPage($warning, $row);

?>